package com.ls.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.config.satoken.SaTokenUtilPy;
import com.ls.controller.template.model.*;
import com.ls.entity.*;
import com.ls.enums.RoleEnum;
import com.ls.enums.TemplateAuditEnum;
import com.ls.enums.TemplateStatusEnum;
import com.ls.exception.SysException;
import com.ls.mapper.SmsTemplateMapper;
import com.ls.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.utils.ExportExcelUtil;
import com.ls.utils.ResultData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.ls.constant.SystemConstants.*;
import static com.ls.constant.SystemConstants.DEFAULT_EXPORT_MAX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author pengyu
 * @since 2024-06-28
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SmsTemplateServiceImpl extends ServiceImpl<SmsTemplateMapper, SmsTemplate> implements ISmsTemplateService {

    private final IRuleTemplateService ruleTemplateService;
    private final IHolidayCategoryService holidayCategoryService;
    private final IHolidayService holidayService;

    /**
     * APP端 新增短信模板
     */
    @Override
    @Transactional(rollbackFor = SysException.class)
    public ResultData add(AddTemplateModel model) {
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP && model.getCallType() == null) {
            return ResultData.failure("请选择通话类型！");
        }
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE && model.getHolidayId() == null) {
            return ResultData.failure("请选择节日！");
        }
        Customer customer;
        SysUser sysUser;
        String phone;
        Long roleId;
        Long sysId = null;
        log.info("新增模板:{}", model);
        //系统模板或者管理员帮用户新增模板
        if (model.getTemplateType() == TEMPLATE_TYPE_SYSTEM || model.getCustomerId() != null) {
            customer = SaTokenUtilPy.getCustomer("PC");
            sysUser = SaTokenUtilPy.getSysUser("APP");
            if (sysUser == null) {
                log.info("sysUser:{}", sysUser);
                return ResultData.failure("管理员才能新增系统模板");
            }
            phone = sysUser.getPhone();
            roleId = sysUser.getRoleId();
            sysId = sysUser.getUserId();
            //用户模板
        } else {
            customer = SaTokenUtilPy.getCustomer();
            phone = customer.getPhone();
            roleId = customer.getRoleId();
        }
        Long customerId = null;
        //用户自己新增
        if (model.getCustomerId() == null && model.getTemplateType() == TEMPLATE_TYPE_USER) {
            customerId = customer.getCustomerId();
            //管理员帮用户新增
        } else if (model.getCustomerId() != null && model.getTemplateType() == TEMPLATE_TYPE_USER) {
            customerId = model.getCustomerId();
            phone = model.getPhone();
        }
        Long count = (long) count(new LambdaQueryWrapper<SmsTemplate>()
                .eq(SmsTemplate::getCallType, model.getCallType())
                .eq(SmsTemplate::getCustomerId, customerId)
        );
        //校验身份
        RoleEnum roleEnum = RoleEnum.getRoleEnum(roleId);
        if (RoleEnum.COMMON.equals(roleEnum) && count > 0) {
            log.info("非会员不能新增模板！,{}", customer);
            return ResultData.noPermission(" 非会员同一类型只能新增一个模板！");
        }
        // 参数校验
        if (model == null || StringUtils.isBlank(model.getTemplateName())) {
            return ResultData.failure("模板名称不能为空！");
        }

        //校验 同一个 customerId templateName唯一
        String templateName = model.getTemplateName();
        SmsTemplate smsTemplate;
        smsTemplate = getOne(new LambdaQueryWrapper<SmsTemplate>()
                .eq(customerId != null, SmsTemplate::getCustomerId, customerId)
                .eq(SmsTemplate::getTemplateCategory, model.getTemplateCategory())
                .eq(model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP && model.getCallType() != null, SmsTemplate::getCallType, model.getCallType())
                .eq(model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE && model.getHolidayId() != null, SmsTemplate::getHolidayId, model.getHolidayId())
                .eq(SmsTemplate::getTemplateType, model.getTemplateType())
                .eq(SmsTemplate::getTemplateName, templateName));
        log.info("查询到的用户:={}", customerId);
        log.info("查询到的模板:={}", smsTemplate);
        if (smsTemplate != null) {
            return ResultData.failure(" 已经存在同名的短信模板！");
        }
        LocalDateTime now = LocalDateTime.now();
        smsTemplate = new SmsTemplate();
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP){
            HangUpTemplateModel hangUpTemplateModel=new HangUpTemplateModel();
            BeanUtils.copyProperties(model, hangUpTemplateModel);
            BeanUtils.copyProperties(hangUpTemplateModel, smsTemplate);
        }else {
            CareTemplateModel careTemplateModel = new CareTemplateModel();
            BeanUtils.copyProperties(model, careTemplateModel);
            BeanUtils.copyProperties(careTemplateModel, smsTemplate);
        }
        smsTemplate.setPhone(phone);
        smsTemplate.setCreateTime(now);
        if (customerId != null) {
            smsTemplate.setCustomerId(customerId);
        } else {
            smsTemplate.setCustomerId(sysId);
        }
        smsTemplate.setUpdateTime(now);
        //会员提交审核
        if (RoleEnum.MEMBER.equals(roleEnum) && model.getTemplateType() == 1) {
            smsTemplate.setTemplateStatus(TemplateStatusEnum.COMMITED.templateStatus);
        } else if (RoleEnum.ADMIN.equals(roleEnum) || model.getCustomerId() != null) {
            smsTemplate.setTemplateStatus(TemplateStatusEnum.APPROVED.templateStatus);
        } else if (RoleEnum.MEMBER.equals(roleEnum) && model.getTemplateType() == 0) {
            log.info("会员不能新增系统模板！");
            return ResultData.failure("会员不能新增系统模板！");
        }
        smsTemplate.setAuditStatus(VALID_FALSE);
        smsTemplate.setCommitTime(now);
        boolean flag = save(smsTemplate);
        if (flag) {
            //TODO 如果有成功的提交审核，那么就应该通知WEB端 websocket
            if (RoleEnum.MEMBER.equals(roleEnum)) {

            }
            return ResultData.success();
        } else {
            return ResultData.failure("内部服务器错误");
        }
    }

    /**
     * 更新短信模板
     */
    @Override
    public ResultData update(EditTemplateModel model) {
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP && model.getCallType() == null) {
            return ResultData.failure("请选择通话类型！");
        }
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE && model.getHolidayId() == null) {
            return ResultData.failure("请选择节日！");
        }
        Long templateId = model.getTemplateId();
        //判断一下是不是本人对应的模板
        SmsTemplate template = getById(templateId);
        if (template == null) {
            return ResultData.failure("模板Id不存在");
        }
        int usageCount = ruleTemplateService.count(
                new LambdaQueryWrapper<RuleTemplate>()
                        .eq(RuleTemplate::getTemplateId, templateId)
        );
        if (usageCount > 0 && model.getTemplateType() == TEMPLATE_TYPE_USER && model.getType() == null) {
            return ResultData.failure("该模板正在使用中，请勿修改！");
        }
        Long customerId = template.getCustomerId();
        Customer customer;
        SysUser sysUser;
        Long roleId;
        Long sysId = null;
        //系统模板
        if (model.getType() != null) {
            customer = SaTokenUtilPy.getCustomer("PC");
            sysUser = SaTokenUtilPy.getSysUser("APP");
            if (sysUser == null) {
                log.info("sysUser:{}", sysUser);
                return ResultData.failure("管理员才能修改系统模板");
            }
            roleId = sysUser.getRoleId();
            sysId = sysUser.getUserId();
            //用户模板
        } else {
            customer = SaTokenUtilPy.getCustomer();
            roleId = customer.getRoleId();
        }
        Long customerIdFromRedis = null;
        if (customer != null) {
            customerIdFromRedis = customer.getCustomerId();
        }
        //校验身份
        RoleEnum roleEnum = RoleEnum.getRoleEnum(roleId);

        //从缓存中取
        if (!customerId.equals(customerIdFromRedis) && RoleEnum.MEMBER.equals(roleEnum) && model.getTemplateType() == 1) {
            return ResultData.failure("不是本人的短信模板，不允许修改");
        }
        // 参数校验
        if (model == null || StringUtils.isBlank(model.getTemplateName())) {
            return ResultData.failure("模板名称不能为空！");
        }

        if (RoleEnum.MEMBER.equals(roleEnum) && model.getTemplateType() == 0) {
            return ResultData.failure("用户不能修改系统模板！");
        }
        //校验 同一个 customerId templateName唯一
        String templateName = model.getTemplateName();
        SmsTemplate smsTemplate;


        smsTemplate = getOne(new LambdaQueryWrapper<SmsTemplate>()
                .eq(customerIdFromRedis != null, SmsTemplate::getCustomerId, customerIdFromRedis)
                .eq(SmsTemplate::getTemplateCategory, model.getTemplateCategory())
                .eq(model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP && model.getCallType() != null, SmsTemplate::getCallType, model.getCallType())
                .eq(model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE && model.getHolidayId() != null, SmsTemplate::getHolidayId, model.getHolidayId())
                .eq(SmsTemplate::getTemplateType, model.getTemplateType())
                .eq(SmsTemplate::getTemplateName, templateName)
                .ne(SmsTemplate::getTemplateId, templateId)
        );
        if (smsTemplate != null) {
            return ResultData.failure("已经存在同名的短信模板");
        }
//        Integer templateStatus = template.getAuditStatus();
        // 修改后就都重新提交审核
        LocalDateTime now = LocalDateTime.now();
        if (!RoleEnum.ADMIN.equals(roleEnum) && model.getTemplateType() == 1) {
            template.setTemplateStatus(TemplateStatusEnum.COMMITED.templateStatus);
        }
        if (model.getType() != null) {
            template.setTemplateStatus(TemplateStatusEnum.APPROVED.templateStatus);
        }
        template.setAuditStatus(VALID_FALSE);
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP){
            HangUpTemplateModel hangUpTemplateModel=new HangUpTemplateModel();
            BeanUtils.copyProperties(model, hangUpTemplateModel);
            BeanUtils.copyProperties(hangUpTemplateModel, template);
        }else {
            CareTemplateModel careTemplateModel = new CareTemplateModel();
            BeanUtils.copyProperties(model, careTemplateModel);
            BeanUtils.copyProperties(careTemplateModel, template);
        }
        template.setCommitTime(now);
        template.setUpdateTime(now);
        boolean flag = updateById(template);
        if (flag) {
            return ResultData.success();
        } else {
            return ResultData.failure("内部服务器错误");
        }
    }

    /**
     * 查询短信模板分页列表
     */
    @Override
    public ResultData pageList(QueryTemplateModel model) {
        log.info("查询短信模板分页列表:{}", model.getBeginSt());
        Customer customer = SaTokenUtilPy.getCustomer("PC");
        Long customerId;
        log.info("用户:{}", customer);
        if (customer != null) {
            customerId = customer.getCustomerId();
            if (model.getTemplateCategory()==null){
                model.setTemplateCategory(TEMPLATE_CATEGORY_HANG_UP);
            }
        } else {
            customerId = null;
        }
        List<Long> holidayIds = new ArrayList<>();
        if (model.getCategoryId()!=null&&model.getHolidayId()==null){
            List<Holiday> holidayList = new ArrayList<>();
            if (model.getCategoryId()==1){
                holidayList=holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .in(Holiday::getCategoryId,  Arrays.asList(1, 2, 3, 4))
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
                log.info("获取所有节假日id:{}", holidayIds);
            }else if (model.getCategoryId()==2){
                holidayIds.add(6L);
            }else {
                holidayList=holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .eq(Holiday::getCategoryId, model.getCategoryId())
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
            }
            if (model.getCategoryId()!=2){
                holidayIds = Optional.ofNullable(holidayList)
                        .orElse(Collections.emptyList())
                        .stream()
                        .map(Holiday::getHolidayId)
                        .collect(Collectors.toList());
            }
        }
        log.info("是否存在用户id:{}", customerId);
        LambdaQueryWrapper<SmsTemplate> wrapper = new LambdaQueryWrapper<SmsTemplate>()
                .and(customerId != null, q -> q
                        .and(subQ -> subQ
                                .eq(SmsTemplate::getCustomerId, customerId)
                                .eq(SmsTemplate::getTemplateType, 1)
                        )
                        .or()
                        .eq(SmsTemplate::getTemplateType, 0)
                )
//                .eq(customerId != null, SmsTemplate::getCustomerId, customerId)
                .like(StringUtils.isNotBlank(model.getPhone()), SmsTemplate::getPhone, model.getPhone())
                .like(StringUtils.isNotBlank(model.getTemplateName()), SmsTemplate::getTemplateName, model.getTemplateName())
                .eq(model.getTemplateCategory() != null, SmsTemplate::getTemplateCategory, model.getTemplateCategory())
                .eq( model.getHolidayId() != null, SmsTemplate::getHolidayId, model.getHolidayId())
                .eq(model.getCallType() != null, SmsTemplate::getCallType, model.getCallType())
                .eq(model.getTemplateType() != null, SmsTemplate::getTemplateType, model.getTemplateType())
                .eq(model.getTemplateStatus() != null, SmsTemplate::getTemplateStatus, model.getTemplateStatus())
                .ge(StringUtils.isNotBlank(model.getBeginSt()), SmsTemplate::getCommitTime, model.getBeginSt())
                .le(StringUtils.isNotBlank(model.getEndSt()), SmsTemplate::getCommitTime, model.getEndSt())
                .in(model.getCategoryId()!=null&&model.getHolidayId()==null&&holidayIds.size()>0,SmsTemplate::getHolidayId,holidayIds)
                .eq(model.getCategoryId()!=null&&model.getHolidayId()==null&&holidayIds.size()==0, SmsTemplate::getHolidayId, -1)
                .orderByAsc(SmsTemplate::getTemplateStatus).orderByDesc(SmsTemplate::getTemplateType).orderByDesc(SmsTemplate::getCreateTime);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        IPage<SmsTemplate> dtoIPage = this.baseMapper.selectPage(page, wrapper);
        //查询这些模板ID 是不是在使用中;如果在的话，就 设置 在使用中
        List<SmsTemplate> templateList = dtoIPage.getRecords();
        if (CollectionUtils.isNotEmpty(templateList)) {
            List<Long> templateIdList = templateList.stream().map(SmsTemplate::getTemplateId).collect(Collectors.toList());
            List<RuleTemplate> ruleTemplateList = ruleTemplateService.list(new LambdaQueryWrapper<RuleTemplate>().in(RuleTemplate::getTemplateId, templateIdList).eq(RuleTemplate::getCustomerId, customerId));
//            Map<Long, String> brigadeMap = ruleTemplateList.stream().collect(Collectors.toMap(RuleTemplate::getTemplateId, Brigade::getBrigadeName));
            Set<Long> set = ruleTemplateList.stream().map(RuleTemplate::getTemplateId).collect(Collectors.toSet());
            templateList.parallelStream().forEach(smsTemplate -> {
                if (set.contains(smsTemplate.getTemplateId())) {
                    smsTemplate.setUseStatus(VALID_TRUE);
                } else {
                    smsTemplate.setUseStatus(VALID_FALSE);
                }
                if (smsTemplate.getHolidayId()!=null){
                    smsTemplate.setHolidayName(holidayService.getById(smsTemplate.getHolidayId()).getHolidayName());
                }
            });
            dtoIPage.setRecords(templateList);
        }
        return ResultData.successData(dtoIPage);
    }
    /**查询模板通过和未通过的数量统计*/
    @Override
    public ResultData summary(TemplateSummaryModel model) {
        log.info("查询短信模板分页列表:{}", model.getBeginSt());
        Customer customer = SaTokenUtilPy.getCustomer("PC");
        Long customerId;
        log.info("用户:{}", customer);
        if (customer != null) {
            customerId = customer.getCustomerId();
            if (model.getTemplateCategory()==null){
                model.setTemplateCategory(TEMPLATE_CATEGORY_HANG_UP);
            }
        } else {
            customerId = null;
        }
        List<Long> holidayIds = new ArrayList<>();
        if (model.getCategoryId()!=null&&model.getHolidayId()==null){
            List<Holiday> holidayList = new ArrayList<>();
            if (model.getCategoryId()==1){
                holidayList=holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .in(Holiday::getCategoryId,  Arrays.asList(1, 2, 3, 4))
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
                log.info("获取所有节假日id:{}", holidayIds);
            }else if (model.getCategoryId()==2){
                holidayIds.add(6L);
            }else {
                holidayList=holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .eq(Holiday::getCategoryId, model.getCategoryId())
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
            }
            if (model.getCategoryId()!=2){
                holidayIds = Optional.ofNullable(holidayList)
                        .orElse(Collections.emptyList())
                        .stream()
                        .map(Holiday::getHolidayId)
                        .collect(Collectors.toList());
            }
        }
        log.info("是否存在用户id:{}", customerId);
        LambdaQueryWrapper<SmsTemplate> wrapper = new LambdaQueryWrapper<SmsTemplate>()
                .and(customerId != null, q -> q
                        .and(subQ -> subQ
                                .eq(SmsTemplate::getCustomerId, customerId)
                                .eq(SmsTemplate::getTemplateType, 1)
                        )
                        .or()
                        .eq(SmsTemplate::getTemplateType, 0)
                )
//                .eq(customerId != null, SmsTemplate::getCustomerId, customerId)
                .like(StringUtils.isNotBlank(model.getPhone()), SmsTemplate::getPhone, model.getPhone())
                .like(StringUtils.isNotBlank(model.getTemplateName()), SmsTemplate::getTemplateName, model.getTemplateName())
                .eq(model.getTemplateCategory() != null, SmsTemplate::getTemplateCategory, model.getTemplateCategory())
                .eq( model.getHolidayId() != null, SmsTemplate::getHolidayId, model.getHolidayId())
                .eq(model.getCallType() != null, SmsTemplate::getCallType, model.getCallType())
                .eq(model.getTemplateType() != null, SmsTemplate::getTemplateType, model.getTemplateType())
                .eq(model.getTemplateStatus() != null, SmsTemplate::getTemplateStatus, model.getTemplateStatus())
                .ge(StringUtils.isNotBlank(model.getBeginSt()), SmsTemplate::getCommitTime, model.getBeginSt())
                .le(StringUtils.isNotBlank(model.getEndSt()), SmsTemplate::getCommitTime, model.getEndSt())
                .in(model.getCategoryId()!=null&&model.getHolidayId()==null&&holidayIds.size()>0,SmsTemplate::getHolidayId,holidayIds)
                .eq(model.getCategoryId()!=null&&model.getHolidayId()==null&&holidayIds.size()==0, SmsTemplate::getHolidayId, -1)
                .orderByAsc(SmsTemplate::getTemplateStatus).orderByDesc(SmsTemplate::getTemplateType).orderByDesc(SmsTemplate::getCreateTime);
        TemplateSummaryVo templateSummaryVo = new TemplateSummaryVo();
        // 获取总数（使用原始条件）
        Integer allQuantity = count(wrapper);
        templateSummaryVo.setAllQuantity(allQuantity);

        // 审核通过数量（克隆原始条件后添加新条件）
        Integer auditedQuantity = count(wrapper.clone().eq(SmsTemplate::getTemplateStatus, TemplateStatusEnum.APPROVED.templateStatus));
        templateSummaryVo.setAuditedQuantity(auditedQuantity);

        // 待审核数量（克隆原始条件后添加新条件）
        Integer commitQuantity = count(wrapper.clone().eq(SmsTemplate::getTemplateStatus, TemplateStatusEnum.COMMITED.templateStatus));
        templateSummaryVo.setCommitQuantity(commitQuantity);

        // 审核未通过数量（克隆原始条件后添加新条件）
        Integer failQuantity = count(wrapper.clone().eq(SmsTemplate::getTemplateStatus, TemplateStatusEnum.FAIL.templateStatus));
        templateSummaryVo.setFailQuantity(failQuantity);

        return ResultData.successData(templateSummaryVo);
    }

    /**
     * 短信模板详情
     */
    @Override
    public ResultData getTemplateById(Long templateId) {
        SmsTemplate template = getById(templateId);
        if (template == null) {
            return ResultData.failure(" 模板Id不在库里：" + templateId);
        }
        return ResultData.successData(template);
    }

    /**
     * 获取审核通过的模板
     */
    @Override
    public ResultData getApprovedTemplate() {
        //实现查询当前登录用户的模板
        Customer customer = SaTokenUtilPy.getCustomer();
        LambdaQueryWrapper<SmsTemplate> wrapper = new LambdaQueryWrapper<SmsTemplate>()
                .eq(SmsTemplate::getCustomerId, customer.getCustomerId())
                .eq(SmsTemplate::getTemplateStatus, TemplateStatusEnum.APPROVED.templateStatus);

        List<SmsTemplate> templateList = list(wrapper);
        if (CollectionUtils.isEmpty(templateList)) {
            return ResultData.successData(templateList);
        }
        return ResultData.successData(templateList);
    }

    /**
     * 审核短信模板
     */
    @Override
    public ResultData audit(AuditTemplateModel model) {
        Long templateId = model.getTemplateId();
        SmsTemplate template = getById(templateId);
        if (template == null) {
            return ResultData.failure(" 模板Id不在库里：" + templateId);
        }
        Integer modelTemplateStatus = model.getTemplateStatus();
        Integer templateStatus = template.getTemplateStatus();
        //3 审核未通过 9 审核通过
        TemplateStatusEnum templateStatusEnum = TemplateStatusEnum.getEnum(modelTemplateStatus);
        if (!TemplateStatusEnum.FAIL.equals(templateStatusEnum) && !TemplateStatusEnum.APPROVED.equals(templateStatusEnum)) {
            return ResultData.successData("审核结果只能是已通过和未通过！");
        }
        template.setTemplateStatus(templateStatusEnum.templateStatus);
        String auditInfo = model.getAuditInfo();
        if (TemplateStatusEnum.FAIL.equals(templateStatusEnum) && StringUtils.isBlank(auditInfo)) {
            return ResultData.successData("审核结果未通过时，审核意见不能为空！");
        }
        //TODO 是否超时未审核（24小时），需要跑定时任务：0 否 1 超时未审核 2 超时已审核
        // 这个字段在审核时不用处理，用每天定时任务来处理
//        template.setAuditStatus();
        if (model.getTemplateStatus() != 3) {
            model.setAuditInfo("");
        }
        BeanUtils.copyProperties(model, template);
        Long userId = StpUtil.getLoginIdAsLong();
        template.setAuditorId(userId);
        boolean flag = updateById(template);
        if (flag) {
            return ResultData.success();
        } else {
            return ResultData.failure("内部服务器错误");
        }
    }


    /**
     * 查询短信模板统计
     */
//    @Override
//    public ResultData summary() {
//        int allQuantity = count(new LambdaUpdateWrapper<SmsTemplate>());
//        int auditedQuantity = count(new LambdaUpdateWrapper<SmsTemplate>()
//                .in(SmsTemplate::getTemplateStatus, TemplateStatusEnum.APPROVED.templateStatus, TemplateStatusEnum.FAIL.templateStatus));
//        int commitQuantity = count(new LambdaUpdateWrapper<SmsTemplate>().eq(SmsTemplate::getTemplateStatus, TemplateStatusEnum.COMMITED));
//        int outTimeAuditQuantity = count(new LambdaUpdateWrapper<SmsTemplate>().eq(SmsTemplate::getAuditStatus, TemplateAuditEnum.OUT_TIME_AUDIT.auditStatus));
//        int outTimeNotAuditQuantity = count(new LambdaUpdateWrapper<SmsTemplate>().eq(SmsTemplate::getAuditStatus, TemplateAuditEnum.OUT_TIME_NOT_AUDIT.auditStatus));
//
//        TemplateSummaryVo vo = new TemplateSummaryVo();
//        vo.setAllQuantity(allQuantity);
//        vo.setAuditedQuantity(auditedQuantity);
//        vo.setCommitQuantity(commitQuantity);
//        vo.setOutTimeAuditQuantity(outTimeAuditQuantity);
//        vo.setOutTimeNotAuditQuantity(outTimeNotAuditQuantity);
//        return ResultData.successData(vo);
//    }

    /**
     * 导出 短信模板 阿里的工具类好像有更优化的方式
     */
    @Override
    public void export(QueryTemplateModel model, HttpServletResponse response) {
        try {
            Page page = new Page(DEFAULT_EXPORT_START, MYBATIS_EXPORT);

            String[] headers = new String[]{"号码", "模板名称", "状态", "类型", "内容"};
            String[] fields = new String[]{"phone", "templateName", "templateStatusStr", "callTypeStr", "agentName"};

            LambdaQueryWrapper<SmsTemplate> wrapper = new LambdaQueryWrapper<SmsTemplate>()
                    .eq(StringUtils.isNotBlank(model.getPhone()), SmsTemplate::getPhone, model.getPhone())
                    .eq(model.getCallType() != null, SmsTemplate::getCallType, model.getCallType())
                    .eq(model.getTemplateStatus() != null, SmsTemplate::getTemplateStatus, model.getTemplateStatus())
                    .ge(StringUtils.isNotBlank(model.getBeginSt()), SmsTemplate::getCommitTime, model.getBeginSt())
                    .le(StringUtils.isNotBlank(model.getEndSt()), SmsTemplate::getCommitTime, model.getEndSt())
                    .orderByDesc(SmsTemplate::getCreateTime).orderByDesc(SmsTemplate::getCommitTime);

            int count = count(wrapper);
            if (count > DEFAULT_EXPORT_MAX) {
                List<String> list = new ArrayList<>(1);
                list.add("导出数量" + count + "不能大于" + DEFAULT_EXPORT_MAX);
                ExportExcelUtil.exportExcel("短信模板.xlsx", headers, fields, new ArrayList<>(), response);
            }
//            IPage<SmsTemplate> dtoIPage = this.baseMapper.selectPage(page, wrapper);

            IPage<SmsTemplate> dtoIPage = this.baseMapper.selectPageList(page, model);


            ExportExcelUtil.exportExcel("企业记录.xlsx", headers, fields, dtoIPage.getRecords(), response);
        } catch (Exception e) {
            log.error("短信模板导出异常,异常信息:{}", e.getMessage());
        }
    }

    /**
     * 删除短信模板
     */
    @Override
    public ResultData del(Long templateId) {
        //和 短信规则绑定了的就不让删除
        int count = ruleTemplateService.count(new LambdaQueryWrapper<RuleTemplate>().eq(RuleTemplate::getTemplateId, templateId));
        if (count > 0) {
            return ResultData.failure("当前模板在使用中，不能删除");
        }
        boolean flag = removeById(templateId);
        if (flag) {
            return ResultData.success();
        } else {
            return ResultData.failure("内部服务器错误");
        }
    }
}
